﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.DBContext;
using Guoc.BigMall.WebService.Dto;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure;
using Guoc.BigMall.Infrastructure.Caching;
using Guoc.BigMall.Infrastructure.WeChat;
using Guoc.BigMall.WebService;
using System.Web;

namespace Guoc.BigMall.WebService.Implement
{
    public class AuthenticateService : IAuthenticateService
    {
        IDBContext _db;
        IWechatService _wechatService;
        ICacheManager _cache;
        ITokenService _tokenService;
        public AuthenticateService(IDBContext dbContext, IWechatService wechatService, ICacheManager cache, ITokenService tokenService)
        {
            _db = dbContext;
            _wechatService = wechatService;
            _cache = cache;
            _tokenService = tokenService;
        }

        /// <summary>
        ///  微信授权登陆
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state">门店Code</param>
        /// <returns></returns>
        public UserContext WechatLogin(string code, string storeCode)
        {

            if (string.IsNullOrEmpty(code))
            {
                throw new FriendlyException("code 参数为空");
            }
            if (string.IsNullOrEmpty(storeCode))
            {
                throw new FriendlyException("storeCode 不能为空");
            }

            var wechatAccount = _db.Table<WechatAccount>().FirstOrDefault(n => n.StoreCode == storeCode);
            if (wechatAccount == null)
            {
                throw new FriendlyException("门店对应的微信app配置缺少");
            }

            //用于模拟微信登录测试
            var openid = "";
            //if (code == "wechat.mock.openid")
            //{
            //    var setting = _db.Table<SystemSetup>().FirstOrDefault(n => n.Name == code);
            //    if (setting == null) { throw new FriendlyException("key [wechat.mock.openid] is not in systemSetup"); }
            //    openid = setting.Value;
            //    var mockUser = _db.Table<Customer>().FirstOrDefault(n => n.UserName == openid);
            //    return CreateUserContext(mockUser, storeCode);
            //}

            // 正常微信登陆
            var accesstoken = _wechatService.GetAccessTokenByCode(code, wechatAccount.AppId, wechatAccount.AppSecret);
            openid = accesstoken.openid;

            var wechatUser = _db.Table<MemberPass>().FirstOrDefault(n => n.PassId == openid && n.PassType == MemberPassType.wechat_openid.ToString());
            if (wechatUser == null)
            {
                //  查询用户信息
                var userInfo = WeChatApi.GetUserInfoNeedAuthorization(accesstoken.access_token, openid);
                wechatUser = new MemberPass()
                {
                    PassId = openid,
                    PassType = MemberPassType.wechat_openid.ToString()
                };
                var newMember = new Member()
                {
                    NickName = userInfo.nickname,
                    HeadImage = userInfo.headimgurl,
                    RealName = userInfo.nickname
                };
                newMember.PassList.Add(wechatUser);
                _db.Insert(newMember);
                _db.SaveChange();
                wechatUser.MemberId = newMember.Id;
            }

            var member = _db.Table<Member>().FirstOrDefault(n => n.Id == wechatUser.MemberId);
            UserContext userContext = new UserContext(member)
            {
                StoreCode = storeCode,
                OpenId = openid
            };


            return CreateUserContext(userContext);
        }

        private UserContext CreateUserContext(UserContext userContext)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add(_tokenService.CurrentUserKey, userContext.MemberId.ToString());
            var expireMin = 60;
            // 创建token
            var token = _tokenService.CreateToken(data, expireMin);
            userContext.Token = token;

            var cacheKey = UserContext.GetCacheKey(userContext.MemberId);
            _cache.Remove(cacheKey);
            _cache.Set(cacheKey, userContext, expireMin);
            return userContext;
        }

        /// <summary>
        ///  微信授权登陆，需要用户同意
        /// </summary>
        /// <param name="code"></param>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        public UserContext LoginNeedAuthenticate(string code, string storeCode)
        {
            // var storeCode = _userContext.Current.StoreCode;
            //var wechatAccount = _db.Table<WechatAccount>().FirstOrDefault(n => n.StoreCode == storeCode);
            //if (wechatAccount == null)
            //{
            //    throw new FriendlyException("门店对应的微信app配置缺少");
            //}


            //// 正常微信登陆
            //var wxTicket = WeChatApi.GetAccessTokenByCode(code, wechatAccount.AppId, wechatAccount.AppSecret);
            //var openid = wxTicket.openid;

            //var userInfo = WeChatApi.GetUserInfoNeedAuthorization(wxTicket.access_token, openid);

            //var wechatUser = _db.Table<Customer>().FirstOrDefault(n => n.UserName == openid);
            //if (wechatUser == null)
            //{
            //    wechatUser = new Customer()
            //    {
            //        UserName = openid,
            //        OpenId = openid,
            //        Platform = Platform.WechatMp,
            //        NickName = userInfo.nickname,
            //        HeadImage = userInfo.headimgurl,
            //        Sex = userInfo.sex,
            //        UnionId = userInfo.unionid
            //    };
            //    _db.Insert(wechatUser);
            //    _db.SaveChange();
            //}
            //else
            //{
            //    // 修改属性
            //    wechatUser.NickName = userInfo.nickname;
            //    wechatUser.HeadImage = userInfo.headimgurl;
            //    wechatUser.Sex = userInfo.sex;
            //    wechatUser.UnionId = userInfo.unionid;
            //    wechatUser.UpdaptedOn = DateTime.Now;
            //    _db.Update(wechatUser);
            //    _db.SaveChange();
            //}

            //// 拿到openid 后做系统登录
            //return CreateUserContext(wechatUser, storeCode);
            throw new Exception("未实现");
        }

        public string GetCodeUrl(string storeCode, string loginUrl)
        {
            var wechatAccount = _db.Table<WechatAccount>().FirstOrDefault(n => n.StoreCode == storeCode);
            if (wechatAccount == null)
            {
                throw new FriendlyException("门店对应的微信app配置缺少");
            }
            // return WeChatApi.Url_Snsapi_base(wechatAccount.AppId, loginUrl, "");
            return WeChatApi.Url_Snsapi_userinfo(wechatAccount.AppId, loginUrl, storeCode);
        }

        public UserContext Login(LoginDto model)
        {

            var identity = _db.Table<MemberPass>().FirstOrDefault(n => n.PassId == model.UserName && n.PassType == MemberPassType.phone.ToString());
            if (identity == null) throw new FriendlyException("用户名或密码错误!");

            var member = _db.Table<Member>().FirstOrDefault(n => n.Id == identity.MemberId);
            if (member == null) throw new FriendlyException("用户名或密码错误!");

            member.CheckAccountState();
            // customer.CheckLoginFailedTimes();
            member.CheckPassword(model.Password);

            var userContext = new UserContext(member)
            {
                StoreCode = model.StoreCode
            };
            // 拿到openid 后做系统登录
            return CreateUserContext(userContext);
        }
    }
}
